//
//  CYABTool.m
//  CreditAddressBook
//
//  Created by Lee on 15/5/18.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYABTool.h"
#import "CYPerson.h"
#import "MJExtension.h"
#import "CYSimpleRecord.h"
#import "AddressBook.h"
#import "UIImageView+WebCache.h"
#import "FMDB.h"
#import "PinYin4Objc.h"
#import "SDWebImageManager.h"
#import "CYLoginHttpTool.h"
#import "CYUser.h"
#import "CYJsonInfo.h"
#import "LECornerImageView.h"
#import "RHPerson+Extension.h"
#import "CYTool.h"
#import "CYPromiseRecordModel.h"
#import "CYDefaultDataTypeModl.h"
#import "CYEscape.h"

@implementation CYABTool

static FMDatabaseQueue *_queue;
static RHAddressBook * _book;
static NSArray *_cypersons;
static NSArray *_rhpersons;

+ (void)initialize {
   // 获取沙盒中数据库的名称
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"by_call_history.sqlite"];
    
    //创建队列
    _queue = [FMDatabaseQueue databaseQueueWithPath:path];
    
    //建表
    [_queue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:@"create table if not exists SC_addressBook (id integer primary key autoincrement, name text, phone text, person blob, RecordID text, create_time double);"];
    }];

    _book = [[RHAddressBook alloc] init];
}

/**
 *  匹配失信联系人
 *
 *  @param params  phones：电话号码组
 *  @param success
 *  @param failure
 */
+ (void)defaultRecordsWithParams:(NSDictionary *)params success:(void (^)(NSArray *cyPersons))success failure:(HttpRequestFailure)failure {
    [CYHttpTool postWithURL:[CYURL defaultRecordsPath] params:params success:^(id json) {
        if (success) {
//            CYLog(@"失信匹配json:%@", json);
            CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
            NSArray *jsonArr = jsonInfo.data;
            if (jsonArr && jsonArr.count) {
                NSMutableArray *arr = [NSMutableArray array];
                NSMutableArray *sections = [NSMutableArray array];
                for (NSDictionary *dic in jsonArr) {
                    CYPerson *cyperson = [[CYPerson alloc] init];
                    
                    CYSimpleRecord *simpRec = [CYSimpleRecord objectWithKeyValues:dic];
                    if (!simpRec.phone || [simpRec.phone isEqualToString:@""]) {
                        continue;
                    }
                    if (simpRec.headPic) {
                        simpRec.headPic = [CYUSERIMAGEBASIC stringByAppendingString:simpRec.headPic];
                    }
                    	
                    //自定义一个RHPerson
//                    RHAddressBook *ab = [[RHAddressBook alloc] init];
//                    RHPerson *rhperson = [ab newPersonInDefaultSource];
//                    rhperson.firstName = @"失信人";
//                    
//                    RHMutableMultiStringValue *rhms = [[RHMutableMultiStringValue alloc] initWithType:kABMultiStringPropertyType];
//                    [rhms addValue:simpRec.phone withLabel:RHPersonPhoneIPhoneLabel];
//                    rhperson.phoneNumbers = rhms;
                    
                    cyperson.simpleRecord = simpRec;
//                    cyperson.person = rhperson;
                    cyperson.pushTag = 1;
                    cyperson.segmentTag = 1;
                    cyperson.iconType = CYIconTypeSX;
                    cyperson.show = YES;
                    
                    [arr addObject:cyperson];
                }
                if (arr.count) {
                    [sections addObject:arr];
                    success(sections);
                } else {
                    if (failure) {
//                        failure(CYError(@"没有更多数据", CYErrorCodeNOData));
                    }
                }
                
            }else {
//                failure(CYError(@"没有更多数据", CYErrorCodeNOData));
            }
            //缓存数据
            
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

/**
 *  根据ID获取违约人详情
 *
 *  @param params  id：ID，type：0:,1:,2:个人发布,3:失信,4:企业虚假,5:个人虚假
 *  @param success
 *  @param failure
 */
+ (void)defaultRecordsbyIdWithParams:(NSDictionary *)params success:(void (^)(NSArray *defrs))success failure:(HttpRequestFailure)failure {
    [CYHttpTool postWithURL:[CYURL defaultRecordsByDefaultIdPath] params:params success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (!jsonInfo.isSuccess) {
            if (failure) {
//                failure(CYError(jsonInfo.message, CYErrorCodeErrorFromService));
                return;
            }
        }
        if (success) {
            NSDictionary *data = jsonInfo.data;
            NSNumber *dayN = data[@"day"];
            long day = dayN.longValue;
            NSArray *defrDics = data[@"list"];
            NSMutableArray *defrs = [NSMutableArray array];
            if ([data[@"list"] isKindOfClass:[NSArray class]] && defrDics.count) {
                for (NSDictionary *defrDic in defrDics) {
                    CYDefaultRecordAO *defr = [CYDefaultRecordAO objectWithKeyValues:defrDic];
                    if (day == 0 || day > 180) {
                        defr.iconTag = -1;
                    }else if (day > 90) {
                        defr.iconTag = 0;
                    }else {
                        defr.iconTag = 1;
                    }
                    [defrs addObject:defr];
                }
            } else if(data[@"promiseRecord"]) {
                CYPromiseRecordModel *promise = [CYPromiseRecordModel objectWithKeyValues:data[@"promiseRecord"]];
                [defrs addObject:promise];
            }
            success(defrs);
            
            //缓存数据
            
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

/**
 *  根据ID获取违约人详情
 *
 *  @param params  id：ID，type：0:,1:,2:个人发布,3:失信,4:企业虚假,5:个人虚假
 *  @param success
 *  @param failure
 */
+ (AFHTTPRequestOperation *)defaultRecordTypeModelsbyIdWithParams:(NSDictionary *)params success:(void (^)(CYDefaultDataTypeModl *model))success failure:(HttpRequestFailure)failure {
    AFHTTPRequestOperation *operation = [CYHttpTool postWithURL:[CYURL defaultRecordsByDefaultIdPath] params:params success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (!jsonInfo.isSuccess) {
            if (failure) {
//                failure(CYError(jsonInfo.message, CYErrorCodeErrorFromService));
                return;
            }
        }
        if (success) {
            NSDictionary *data = jsonInfo.data;
            NSNumber *dayN = data[@"day"];
            long day = dayN.longValue;
            NSArray *defrDics = data[@"defaultRecordList"];
            NSMutableArray *defrs = [NSMutableArray array];
            CYDefaultDataTypeModl *model = [CYDefaultDataTypeModl new];
            if ([data[@"defaultRecordList"] isKindOfClass:[NSArray class]] && defrDics.count) {
                for (NSDictionary *defrDic in defrDics) {
                    CYDefaultRecordAO *defr = [CYDefaultRecordAO objectWithKeyValues:defrDic];
                    if (day == 0 || day > 180) {
                        defr.iconTag = -1;
                    }else if (day > 90) {
                        defr.iconTag = 0;
                    }else {
                        defr.iconTag = 1;
                    }
                    [defrs addObject:defr];
                }
                model.defaults = defrs;
                model.type = 0;
            } else if(data[@"promiseList"]) {
                NSArray *promiseList = [CYPromiseRecordModel objectArrayWithKeyValuesArray:data[@"promiseList"]];
                [defrs addObjectsFromArray:promiseList];
                model.defaults = defrs;
                model.type = 1;
            }
            success(model);
            //缓存数据
            
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
    return operation;
}

/**
 *  疑似失信人
 *
 *  @param params
 *  @param success
 *  @param failure
 */
+ (AFHTTPRequestOperation *)ysDefaultPersonsWithParams:(NSDictionary *)params success:(void (^)(NSArray *defrs))success failure:(HttpRequestFailure)failure {
    AFHTTPRequestOperation *operation = [CYHttpTool postWithURL:[CYURL ysDefaultPersonsPath] params:params success:^(id json) {
//        CYLog(@"%@", json);
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            NSArray *arr = jsonInfo.data;
            if (success && arr.count) {
                NSMutableArray *persons = [NSMutableArray array];
                for (NSDictionary *dic in arr) {
                    CYPerson *person = [CYPerson objectWithKeyValues:dic];
                    person.pushTag = 1;
                    person.segmentTag = 2;
                    person.iconType = CYIconTypeYS;
                    person.show = YES;
                    [persons addObject:person];
                }
                success(persons);
            } else {
                if (failure) {
//                   failure(CYError(@"没有跟多数据", CYErrorCodeNOData));
                }
            }
        } else {
            if (failure) {
//                failure(CYError(json[@"message"], CYErrorCodeParamsError));
            }
        }
    } failure:^(NSError *error) {
        CYLog(@"疑似失信人匹配失败：%@", error);
        if (failure) {
            failure(error);
        }
    }];
    
    return operation;
}

/**
 *  根据姓名匹配失信人
 *
 *  @param params
 *  @param success
 *  @param failure
 */
+ (void)defaultRecordsByNameWithParams:(NSDictionary *)params success:(void (^)(NSArray *defrs))success failure:(HttpRequestFailure)failure {
    [CYHttpTool postWithURL:[CYURL defaultRecordsBySearchPath] params:params success:^(id json) {
//        CYLog(@"%@", json);
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        NSArray *arr = jsonInfo.data[@"content"];
        if (arr && arr.count) {
            NSMutableArray *defrs = [NSMutableArray array];
            for (NSDictionary *defrDic in arr) {
                CYDefaultRecordAO *defr = [CYDefaultRecordAO objectWithKeyValues:defrDic];
                [defrs addObject:defr];
            }
            if (success) {
                success(defrs);
            }
        } else {
            if (failure) {
//                failure(CYError(@"没有数据", CYErrorCodeNOData));
            }
        }
        
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

/**
 *  通讯录图片DIY设置
 *
 *  @param params
 *  @param success
 *  @param failure
 */
+ (void)imageSelectPageWithKey:(NSString *)key page:(NSInteger)page flag:(NSInteger)flag success:(void (^)(NSArray *defrs))success failure:(HttpRequestFailure)failure {
//    CYLog(@"%@", params);
    [CYHttpTool postWithURL:[CYURL imageSelectPagePath] params:@{@"name": @"图片", @"page": @(page), @"flag": @(flag)} success:^(id json) {
        //        CYLog(@"%@", json);
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            NSDictionary *messageDic = jsonInfo.data;
            NSArray *urls = messageDic[@"imageUrls"];
            
            if (success) {
                success(urls);
            }
        } else {
            if (failure) {
//                failure(CYError(@"错误", CYErrorCodeParamsError));
            }
        }
    } failure:^(NSError *error) {
        CYAlertView(@"cuowo");
        CYLog(@"通讯录图片设置失败%@", error);
    }];
}

/**
 *  通讯录图片DIY设置
 *
 *  @param params
 *  @param success
 *  @param failure
 */
+ (void)imageSelectPageWithParams:(NSDictionary *)par success:(void (^)(NSArray *defrs))success failure:(HttpRequestFailure)failure {
    //    CYLog(@"%@", params);
    [CYHttpTool postWithURL:[CYURL imageSelectPagePath] params:par success:^(id json) {
        //        CYLog(@"%@", json);
        if (json && [json[@"success"] equals:@"success"]) {
            NSDictionary *messageDic = json[@"message"];
            NSArray *urls = messageDic[@"imageUrls"];
            
            if (success) {
                success(urls);
            }
        } else {
            if (failure) {
//                failure(CYError(@"错误", CYErrorCodeParamsError));
            }
        }
    } failure:^(NSError *error) {
        CYAlertView(@"cuowo");
        CYLog(@"通讯录图片设置失败%@", error);
    }];
}

/**
 *  通讯录图片设置
 *
 *  @param params
 *  @param success
 *  @param failure
 */
+ (void)imageSelectOneWithParams:(NSDictionary *)params success:(void (^)(NSArray *defrs))success failure:(HttpRequestFailure)failure {
    [CYHttpTool postWithURL:[CYURL imageSelectOnePath] params:params success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            NSDictionary *messageDic = jsonInfo.message;
            NSArray *urls = messageDic[@"imageUrls"];
            if (urls && urls.count) {
                if (success) {
                    success(urls);
                }
            }
        } else {
            
        }
    } failure:^(NSError *error) {
        CYLog(@"通话记录图片设置失败%@", error);
    }];
}

/**
 *  下载一张图片
 */
+ (void)downloadImageWithURL:(NSString *)url progress:(void (^)(NSInteger receivedSize, NSInteger expectedSize))progressBlock success:(void (^)(UIImage *image))success {
    [SDWebImageDownloader.sharedDownloader downloadImageWithURL:[NSURL URLWithString:url] options:0 progress:progressBlock completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
        if (image) {
            if (success) {
                success(image);
            }
        }
    }];
}
/**
 *  根据姓名或者性别或者地域进行疑似联系人筛选
 */
+ (void)getDefaultRecordsByCityAndSexWithParam:(NSDictionary *)param success:(void(^)(NSArray *defrs))success failure:(HttpRequestFailure1)failure {
    [CYHttpTool postWithURL:[CYURL shared].getDefaultRecordsByCityAndSex params:param success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            NSArray *defaultRecords = [CYDefaultRecordAO objectArrayWithKeyValuesArray:jsonInfo.data];
            if (success) {
                success(defaultRecords);
            }
        } else {
            if (failure) {
                failure(jsonInfo.message, nil);
            }
        }
    } failure:^(NSError *error) {
        CYLog(@"疑似联系人筛选错误：%@", error);
        if (failure) {
            failure(nil, error);
        }
    }];
}

/**
 *  存储一条数据
 *
 *  @param person
 */
+ (void)addCYPerson:(CYPerson *)person {
    [_queue inDatabase:^(FMDatabase *db) {
        NSData *personData = [NSKeyedArchiver archivedDataWithRootObject:person.person];
        NSData *simpleRecordData = [NSKeyedArchiver archivedDataWithRootObject:person.simpleRecord];
        
        //存数据
        [db executeUpdate:@"insert or replace into t_addressBook (pinyin, pinyinHeader, pinyinHeaderFirst, name, phone, person, simpleRecord, create_time) values(?, ?, ?, ?, ?, ?, ?, ?)", person.pinyin, person.pinyinHeader, person.pinyinHeaderFirst, person.name, person.phone, personData, simpleRecordData, [NSDate date]];
    }];
}

/**
 *  存储N条数据
 *
 *  @param persons
 */
+ (void)addCYPersons:(NSArray *)persons {
    for (CYPerson *person in persons) {
        [self addCYPerson:person];
    }
}

/**
 *  查找CYPerson
 *
 *  @param query:查询条件
 *
 *  @return
 */
+ (NSArray *)personsWithParam:(NSDictionary *)param {
    __block NSMutableArray *arr = nil;
    
    [_queue inDatabase:^(FMDatabase *db) {
        arr = [NSMutableArray array];
        
        FMResultSet *rs = nil;
        if (param[@"query"]) {
            rs = [db executeQuery:@"select * from t_addressBook where pinyin = ? or pinyinHeader = ? or pinyinHeaderFirst = ? or name = ? or phone = ?", param[@"query"], param[@"query"], param[@"query"], param[@"query"], param[@"query"]];
        }
        
        while (rs.next) {
            NSString *name = [rs stringForColumn:@"name"];
            NSString *phone = [rs stringForColumn:@"phone"];
            NSData *person = [rs dataForColumn:@"person"];
            NSData *simpleRecord = [rs dataForColumn:@"simpleRecord"];
            
            CYPerson *cyPerson = [[CYPerson alloc] initWithRHPerson:[NSKeyedUnarchiver unarchiveObjectWithData:person]];
            cyPerson.name = name;
            cyPerson.phone = phone;
            cyPerson.simpleRecord = [NSKeyedUnarchiver unarchiveObjectWithData:simpleRecord];
            
            [arr addObject:cyPerson];
        }
    }];
    
    return arr;
}

/**
 *  将RHPerson转为CYPerson
 *
 *  @param rhPerson
 *
 *  @return
 */
+ (CYPerson *)cyPersonFromRHPerson:(RHPerson *)rhPerson {
    CYPerson *cyPerson = [[CYPerson alloc] initWithRHPerson:rhPerson];
    return cyPerson;
}

/**
 *  将RHPersons转为CYPersons
 *
 *  @param rhPersons
 *
 *  @return
 */
+ (NSArray *)cyPersonsFromRHPersons:(NSArray *)rhPersons {
    if (!_cypersons) {
        NSMutableArray *arr = [NSMutableArray array];
        for (RHPerson *rhPerson in rhPersons) {
            CYPerson *cyPerson = [self cyPersonFromRHPerson:rhPerson];
            [arr addObject:cyPerson];
        }
        _cypersons = arr;
    }
    return _cypersons;
}

/**
 *  格式化电话号码
 */
+ (NSArray *)formatPhoneNumbers:(NSArray *)phones {
    if (!phones || !phones.count) {
        return @[@"---"];
    }
    NSMutableArray *arr = [NSMutableArray array];
    for (NSString *phone in phones) {
        [arr addObject:[self formatPhoneNumber:phone]];
    }
    return arr;
}

+ (NSString *)formatPhoneNumber:(NSString *)formatePhone {
    if ([formatePhone rangeOfString:@"-"].length) {
        formatePhone = [formatePhone stringByReplacingOccurrencesOfString:@"-" withString:@""];
    }
    if ([formatePhone rangeOfString:@"("].length) {
        formatePhone = [formatePhone stringByReplacingOccurrencesOfString:@"(" withString:@""];
        formatePhone = [formatePhone stringByReplacingOccurrencesOfString:@")" withString:@""];
    }
    if ([formatePhone rangeOfString:@"·"].length) {
        formatePhone = [formatePhone stringByReplacingOccurrencesOfString:@"·" withString:@""];
    }
    if ([formatePhone rangeOfString:@" "].length) {
        formatePhone = [formatePhone stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    if ([formatePhone rangeOfString:@" "].length) {//\u00A0空格
        formatePhone = [formatePhone stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    if ([formatePhone rangeOfString:@"+86"].length) {
        formatePhone = [formatePhone stringByReplacingOccurrencesOfString:@"+86" withString:@""];
    }
    if (formatePhone.length > 20) {
//        CYLog(@"%@长度过长：%lu", formatePhone, (unsigned long)formatePhone.length);
        [self reportReason:CYStringFormat(@"%@长度过长：%lu", formatePhone, (unsigned long)formatePhone.length)];
        formatePhone = [formatePhone substringToIndex:20];
    }
    return formatePhone;
}

+ (RHAddressBook *)addressBook {
    return _book;
}
/**
 *  读取通讯录联系人
 *
 *  @return
 */
+ (NSArray *)accessAllPeople {
    //判断是否获得通讯录权限
    if ([RHAddressBook authorizationStatus] != RHAuthorizationStatusAuthorized) return nil;
    if (!_rhpersons) {
        
        NSArray *peoples = [_book people];
        
        //祛除空联系人
        NSMutableArray *rhPerson = [NSMutableArray array];
        for (RHPerson *person in peoples) {
            NSArray *phones = person.formatterPhones;
            if (phones.count) {
                [rhPerson addObject:person];
            }
        }
        _rhpersons = rhPerson;
    }
    return _rhpersons;
}

/**
 *  重新读取通讯录联系人
 *
 *  @return
 */
+ (NSArray *)reloadAllPeople {
    //判断是否获得通讯录权限
    if ([RHAddressBook authorizationStatus] != RHAuthorizationStatusAuthorized) return nil;
    
    NSArray *peoples = [_book people];
    
    //祛除空联系人
    NSMutableArray *rhPerson = [NSMutableArray array];
    for (RHPerson *person in peoples) {
        if (person.formatterPhones.count) {
            [rhPerson addObject:person];
        }
    }
    _rhpersons = rhPerson;
    _cypersons = nil;
    return rhPerson;
}

+ (RHPerson *)rhPersonWithName:(NSString *)name phones:(NSArray *)phones {
    NSArray *persons = [self reloadAllPeople];
    
    //格式化电话号码与名字
    phones = [CYABTool formatPhoneNumbers:phones];
//    name = [CYTool formatName:name];
    
    if (name && phones && phones.count) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"formatterName == %@", name];
        NSArray *names = [persons filteredArrayUsingPredicate:predicate];
        for (RHPerson *person in names) {
            NSArray *personPhones = person.formatterPhones;
            if ([personPhones isEqualToArray:phones]) {
                return person;
            } else if ([self arrIncludeArr:personPhones arr2:phones]) {
                return person;
            }
        }
    } else if (phones && phones.count) {
        for (RHPerson *person in persons) {
            NSArray *personPhones = person.formatterPhones;
            if ([personPhones isEqualToArray:phones]) {
                return person;
            } else if ([self arrIncludeArr:personPhones arr2:phones]) {
                return person;
            }
        }
    }
    return nil;
}

//判定一个数组是否包含在另一个数据中
+ (BOOL)arrIncludeArr:(NSArray *)arr1 arr2:(NSArray *)arr2 {
    NSMutableSet *arr1Set = [NSMutableSet setWithArray:arr1];
    NSInteger arr1Count = arr1Set.count;
    NSMutableSet *arr2Set = [NSMutableSet setWithArray:arr2];
    NSInteger arr2Count = arr2Set.count;
    if (arr1 > arr2) {
        [arr1Set addObjectsFromArray:arr2];
        if (arr1Set.count == arr1Count) {
            return YES;
        }
        return NO;
    } else {
        [arr2Set addObjectsFromArray:arr1];
        if (arr2Set.count == arr2Count) {
            return YES;
        }
        return NO;
    }
}

+ (void)jfshopWithType:(NSString *)type success:(void (^)(NSString *message))success failure:(HttpRequestFailure)failure {
    @try {
        CYUser *user = [CYLoginHttpTool  userData].user;
        if (user) {
            NSDictionary *data = @{@"type":type,@"userId":user.userId, @"token": user.token};
            NSString *dataStr = [NSString jsonStringWithDictionary: data];
            [CYHttpTool postWithURL:[CYURL addCredit] params:@{@"data" :dataStr} success:^(id json) {
                CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
                if (jsonInfo.isSuccess) {
                    if (success) {
                        success(CYStringFormat(@"%@", jsonInfo.message));
                    }
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"addCread"object:nil];
                } else {
                    if (failure) {
//                        failure(CYError(@"失败", CYErrorCodeNOData));
                    }
                }
            } failure:^(NSError *error) {
                CYLog(@"失败:%@",error);
                if (failure) {
                    failure(error);
                }
            }];
        }
    }
    @catch (NSException *exception) {
        NSAssert1(NO, @"积分累加错误: %@", exception);
        if (failure) {
//            failure(CYError(@"积分累加错误", CYErrorCodeErrorFromService));
        }
    }

}


@end
